<?php

declare(strict_types=1);

namespace App\Chat\Service;

use App\CustHub\Mapper\ChTalkUserExtendInfoMapper;
use FriendsOfHyperf\Lock\Exception\LockTimeoutException;
use Hyperf\DbConnection\Db;
use Mine\Abstracts\AbstractService;
use function FriendsOfHyperf\Lock\lock;

class ChTalkUserExtendInfoService extends AbstractService
{
    public $mapper;

    public function __construct(ChTalkUserExtendInfoMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    public function getInfo(array $params): array
    {
        $info = $this->mapper->getInfo((int)$params['uid'],$params['user_id']);
        if(empty($info)){
            $columns = Db::select("SHOW FULL COLUMNS FROM ch_talk_user_extend_info");

            $defaultConfig = [];
            foreach ($columns as $column) {
                $field = $column->Field;
                $default = $column->Default;

                // 跳过自增主键和时间字段
                if (in_array($field, ['id', 'created_at', 'updated_at'])) {
                    continue;
                }

                // UID 填当前用户
                if ($field === 'cs_id') {
                    $defaultConfig[$field] = $params['uid'];
                }elseif ($field === 'user_id'){
                    $defaultConfig[$field] = $params['user_id'];
                }elseif ($field === 'deal_status'){
                    $defaultConfig[$field] = [];
                } else {
                    $defaultConfig[$field] = $default ?? '';
                }
            }
            return $defaultConfig;
        }
        return $info->toArray();
    }

    public function saveUserExtInfo(array $data)
    {
        $lock = lock('ch_talk_user_extend_info_lock:'.$data['uid'].$data['user_id'],4);

        try {
            $lock->block(2);

            $data['cs_id'] = $data['uid'];
            if(empty($data['deal_status'])){
                $data['deal_status'] = [];
            }else{
                $data['deal_status'] = json_decode($data['deal_status'],true);
            }

            $info = $this->mapper->getInfo((int)$data['uid'],$data['user_id']);
            if(empty($info)){
                $rst = $this->mapper->save($data);
            }else{
                $rst = $this->mapper->update($info->id,$data);
            }
            if($rst){
                echo 12;
                $this->mapper->clearCache((int)$data['uid'],$data['user_id']);
            }
            return $rst;
        }catch (LockTimeoutException $e){
            return false;
        } finally {
            $lock->release();
        }
    }
}